package com.yangwei.examination.teacher.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yangwei.examination.teacher.mappers.PaperQuestionAnswerDtoMapper;
import com.yangwei.examination.teacher.mappers.PaperQuestionChoiceDtoMapper;
import com.yangwei.examination.teacher.mappers.PaperQuestionDtoMapper;
import com.yangwei.examination.teacher.model.PaperMakerParam;
import com.yangwei.examination.teacher.pojo.*;
import com.yangwei.examination.teacher.service.*;
import com.yangwei.examination.utils.ResultUtils;

import com.yangwei.examination.utils.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "教师编辑试卷",description = "试题及试卷创建")
@RestController
@RequestMapping("/tea/Paper")
public class PaperController {

    @Resource
    private PaperService paperService;

    @Resource
    private PaperQuestionService paperQuestionService;

    @Resource
    private PaperQuestionChoiceService paperQuestionChoiceService;

    @Resource
    private PaperQuestionAnswerService paperQuestionAnswerService;

    @Resource
    private BankQuestionService bankQuestionService;

    @Resource
    private BankQuestionAnswerService bankQuestionAnswerService;

    @Resource
    private BankQuestionChoiceService bankQuestionChoiceService;

    //获取试卷列表及其所有数据
    @ApiOperation("获取试卷列表及其所有数据")
    @GetMapping("/list")
    public ResultVo getPaperListAndData() {
        //全查Paper
        List<Paper> paperList = paperService.list(Wrappers.lambdaQuery(Paper.class)
                .orderByDesc(Paper::getId)
        );
        //注入Paper中的PaperQuestionList
        for (Paper paper : paperList) {
            QueryWrapper<PaperQuestion> paperQuestionQuery = new QueryWrapper<>();
            //按试题的排序查询
            paperQuestionQuery.lambda().eq(PaperQuestion::getPaperId, paper.getId()).
                    orderByAsc(PaperQuestion::getQuestionOrder);
            List<PaperQuestion> paperQuestionList = paperQuestionService.list(paperQuestionQuery);
            //在每个Question中注入PaperQuestionChoiceList
            for (PaperQuestion paperQuestion : paperQuestionList) {

                //对问题paperQuestion注入选项PaperQuestionChoice
                //题目选项总是会按ChoiceOrder的编号升序排列 orderByAsc(PaperQuestionChoice::getChoiceOrder);
                QueryWrapper<PaperQuestionChoice> paperQuestionChoiceQuery = new QueryWrapper<>();
                paperQuestionChoiceQuery.lambda().eq(PaperQuestionChoice::getQuestionId, paperQuestion.getId()).orderByAsc(PaperQuestionChoice::getChoiceOrder);
                List<PaperQuestionChoice> paperQuestionChoiceList = paperQuestionChoiceService.list(paperQuestionChoiceQuery);
                paperQuestion.setPaperQuestionChoiceList(paperQuestionChoiceList);

                //对问题paperQuestion注入答案PaperQuestionAnswer
                //题目答案总是会按AnswerOrder的编号升序排列 orderByAsc(PaperQuestionAnswer::getAnswerOrder);
                QueryWrapper<PaperQuestionAnswer> paperQuestionAnswerQuery = new QueryWrapper<>();
                paperQuestionAnswerQuery.lambda().eq(PaperQuestionAnswer::getQuestionId, paperQuestion.getId()).orderByAsc(PaperQuestionAnswer::getAnswerOrder);
                List<PaperQuestionAnswer> paperQuestionAnswerList = paperQuestionAnswerService.list(paperQuestionAnswerQuery);
                paperQuestion.setPaperQuestionAnswerList(paperQuestionAnswerList);
            }
            paper.setPaperQuestionList(paperQuestionList);
        }

        //注入paperInfo
        for (Paper paper : paperList) {
            PaperInfo paperInfo = new PaperInfo();
            for (int i = 1; i <= 4; i++) {
                QueryWrapper<PaperQuestion> paperQuestionQueryCount = new QueryWrapper<>();
                paperQuestionQueryCount.lambda().eq(PaperQuestion::getQuestionType, i).eq(PaperQuestion::getPaperId, paper.getId());
                if (i == 1)
                    paperInfo.setSingleNum(paperQuestionService.count(paperQuestionQueryCount));
                if (i == 2)
                    paperInfo.setMultipleNum(paperQuestionService.count(paperQuestionQueryCount));
                if (i == 3)
                    paperInfo.setFillInNum(paperQuestionService.count(paperQuestionQueryCount));
                if (i == 4)
                    paperInfo.setTextNum(paperQuestionService.count(paperQuestionQueryCount));
            }
            paper.setPaperInfo(paperInfo);
        }

        return ResultUtils.success("查询成功", paperList);
    }


    //调试使用
    @ApiOperation("删除试卷信息-前端未使用仅调试")
    @GetMapping("/delete")
    @Transactional
    public ResultVo delete(@ApiParam(name = "id",value = "paperId唯一") @RequestParam("id") Long id) {

        List<PaperQuestion> paperQuestionList = paperQuestionService.list(Wrappers.lambdaQuery(PaperQuestion.class)
                .eq(PaperQuestion::getPaperId, id)
        );

        //逻辑判空
        if (paperQuestionList.size() != 0) {

            for (PaperQuestion paperQuestion : paperQuestionList) {

                if (paperQuestion.getQuestionType().equals("1") || paperQuestion.getQuestionType().equals("2")) {

                    //1.删除选项信息
                    List<PaperQuestionChoice> paperQuestionChoiceList = paperQuestionChoiceService.list(Wrappers.lambdaQuery(PaperQuestionChoice.class)
                            .eq(PaperQuestionChoice::getQuestionId, paperQuestion.getId())
                    );
                    //逻辑判空
                    if (paperQuestionChoiceList.size() != 0) {
                        List<Long> paperQuestionChoiceIds = paperQuestionChoiceList.stream().map(PaperQuestionChoice::getId).collect(Collectors.toList());
                        paperQuestionChoiceService.removeByIds(paperQuestionChoiceIds);
                    }

                }

                //2.删除答案信息
                List<PaperQuestionAnswer> paperQuestionAnswerList = paperQuestionAnswerService.list(Wrappers.lambdaQuery(PaperQuestionAnswer.class)
                        .eq(PaperQuestionAnswer::getQuestionId, paperQuestion.getId())
                );
                //逻辑判空
                if (paperQuestionAnswerList.size() != 0) {
                    List<Long> paperQuestionAnswerIds = paperQuestionAnswerList.stream().map(PaperQuestionAnswer::getId).collect(Collectors.toList());
                    paperQuestionAnswerService.removeByIds(paperQuestionAnswerIds);
                }

            }

        }
        //删除本身paperQuestionList
        paperQuestionService.removeByIds(
                paperQuestionList.stream().map(PaperQuestion::getId).collect(Collectors.toList())
        );

        //删除paper
        paperService.removeById(id);

        return null;
    }

    //编撰试卷 将bankQuestionList保存
    @ApiOperation("组卷")
    @PostMapping("/save")
    @Transactional
    public ResultVo save(@RequestBody PaperMakerParam paperMakerParam) {

        Paper paper = new Paper();
        paper.setPaperTitle(paperMakerParam.getPaperTitle());
        paper.setPaperDesc(paperMakerParam.getPaperDesc());
        paper.setPaperStatus("1");
        boolean savePaper = paperService.save(paper);

        Long paperId = null;
        if (savePaper) {
            paperId = paper.getId();
        }

//        Long[] idsArray = paperMakerParam.getIds();
//        List<Long> idsList = Arrays.asList(idsArray);

        //查题库信息
        List<BankQuestion> bankQuestionList = bankQuestionService.list(Wrappers.lambdaQuery(BankQuestion.class)
                .in(BankQuestion::getId, paperMakerParam.getIds())
        );

        // 将 ids 转换为 Set，以便能够快速检查元素是否存在在集合中
        // 使用 Stream 进行过滤和排序
        //为了让其按原始id顺序排列
        List<Long> ids = paperMakerParam.getIds();  // 原始的 ids 列表
        Set<Long> idsSet = new HashSet<>(ids);
        List<BankQuestion> sortedBankQuestionList = bankQuestionList.stream()
                .filter(question -> idsSet.contains(question.getId()))
                .sorted(Comparator.comparing(question -> ids.indexOf(question.getId())))
                .collect(Collectors.toList());


        for (BankQuestion bankQuestion : sortedBankQuestionList) {
            //选择题题目需要选项
            if (bankQuestion.getQuestionType().equals("1") || bankQuestion.getQuestionType().equals("2")) {
                bankQuestion.setBankQuestionChoiceList(
                        bankQuestionChoiceService.list(Wrappers.lambdaQuery(BankQuestionChoice.class)
                                .eq(BankQuestionChoice::getQuestionId, bankQuestion.getId())
                                .orderByAsc(BankQuestionChoice::getChoiceOrder)
                        )
                );
            }
            //查答案
            bankQuestion.setBankQuestionAnswerList(
                    bankQuestionAnswerService.list(Wrappers.lambdaQuery(BankQuestionAnswer.class)
                            .eq(BankQuestionAnswer::getQuestionId, bankQuestion.getId())
                            .orderByAsc(BankQuestionAnswer::getAnswerOrder)
                    )
            );
            System.out.println("测试" + bankQuestion);
        }


        //*使用mapStruct进行高性能映射
        List<PaperQuestion> paperQuestionList = new ArrayList<>();
        int order = 1;
        for (BankQuestion bankQuestion : sortedBankQuestionList) {
            PaperQuestion paperQuestion = PaperQuestionDtoMapper.INSTANCE.toPaperQuestionDto(bankQuestion);
            paperQuestion.setQuestionOrder(order++);
            paperQuestion.setPaperId(paperId);
            boolean savePaperQuestion = paperQuestionService.save(paperQuestion);
            Long paperQuestionId = null;
            if (savePaperQuestion) {
                paperQuestionId = paperQuestion.getId();  //获取自增id
            }

            if (paperQuestion.getQuestionType().equals("1") || paperQuestion.getQuestionType().equals("2")) {

                List<PaperQuestionChoice> paperQuestionChoiceList = PaperQuestionChoiceDtoMapper.INSTANCE.toPaperQuestionChoiceListDto(bankQuestion.getBankQuestionChoiceList());
                //注入paperQuestion自增id
                for (PaperQuestionChoice PaperQuestionChoice : paperQuestionChoiceList) {
                    PaperQuestionChoice.setQuestionId(paperQuestionId);
                }
                paperQuestionChoiceService.saveBatch(paperQuestionChoiceList);
            }

            List<PaperQuestionAnswer> paperQuestionAnswerList = PaperQuestionAnswerDtoMapper.INSTANCE.toPaperQuestionAnswerListDto(bankQuestion.getBankQuestionAnswerList());
            //注入paperQuestion自增id
            for (PaperQuestionAnswer paperQuestionAnswer:paperQuestionAnswerList){
                paperQuestionAnswer.setQuestionId(paperQuestionId);
            }
            paperQuestionAnswerService.saveBatch(paperQuestionAnswerList);

            paperQuestionList.add(paperQuestion);
        }


        System.out.println(paperMakerParam);

        return ResultUtils.success("试卷保存成功！", paperQuestionList);
    }


}
